package com.payment.ktb.activity.main4;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.payment.ktb.Interface.AlertInterface;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.activity.BaseActivity;
import com.payment.ktb.constants.Constants;
import com.payment.ktb.constants.ConstantsUser;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.Md5Utils;
import com.payment.ktb.utils.PhtotUtils;
import com.payment.ktb.utils.SharedPreferencesUtils;
import com.payment.ktb.utils.StringUtils;
import com.payment.ktb.utils.ToastUtils;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by syd on 2016/6/29.
 */
public class BasicalInfoActivity extends BaseActivity {


    File file = new File(Environment.getExternalStorageDirectory(), "realnameauth.png");


    @BindView(R.id.et_basicalinfo_name)
    EditText et_basicalinfo_name;
    @BindView(R.id.et_basicalinfo_identification)
    EditText et_basicalinfo_identification;
    @BindView(R.id.tv_basicalinfo_notes)
    TextView tv_basicalinfo_notes;
    @BindView(R.id.iv_basicalinfo_pic1)
    ImageView iv_basicalinfo_pic1;
    @BindView(R.id.iv_basicalinfo_pic2)
    ImageView iv_basicalinfo_pic2;
    @BindView(R.id.iv_basicalinfo_pic4)
    ImageView iv_basicalinfo_pic4;
    @BindView(R.id.btn_basicalinfo_confirm)
    Button btn_basicalinfo_confirm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_basicalinfo);
        initTitle("基本信息");
        ButterKnife.bind(this);
        initView();

    }

    /**
     *
     */
    private void savaInfo() {
        if (!TextUtils.isEmpty(et_basicalinfo_identification.getText().toString().trim())) {
            SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.SHOPCERT,et_basicalinfo_identification.getText().toString().trim());
        }
        if (!TextUtils.isEmpty(et_basicalinfo_name.getText().toString().trim())) {
            SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.SHOPACCOUNT,et_basicalinfo_name.getText().toString().trim());
        }
    }

    private void initView() {
        et_basicalinfo_name.setText(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.SHOPACCOUNT));
        et_basicalinfo_identification.setText(StringUtils.handelIDNO(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.SHOPCERT)));

        if (!TextUtils.isEmpty(ConstantsUser.showMsg)) {
            tv_basicalinfo_notes.setVisibility(View.VISIBLE);
            tv_basicalinfo_notes.setText(ConstantsUser.showMsg);
        } else {
            tv_basicalinfo_notes.setVisibility(View.GONE);
        }


        //image1
        if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC1))) {
            Picasso.with(mContext).load(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC1)).error(R.drawable.basic_img).fit().into(iv_basicalinfo_pic1);
        }

        if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC2))) {
            Picasso.with(mContext).load(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC2)).error(R.drawable.basic_img).fit().into(iv_basicalinfo_pic2);
        }


        if (!TextUtils.isEmpty(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC4))) {
            Picasso.with(mContext).load(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC4)).error(R.drawable.basic_img).fit().into(iv_basicalinfo_pic4);
        }

        /**
         * 基本信息是否可以编辑
         */
        if ("0".equals(ConstantsUser.isEdit)) {
            et_basicalinfo_name.setEnabled(false);
            et_basicalinfo_identification.setEnabled(false);
            btn_basicalinfo_confirm.setVisibility(View.GONE);
        } else {
            et_basicalinfo_name.setEnabled(true);
            et_basicalinfo_identification.setEnabled(true);
            btn_basicalinfo_confirm.setVisibility(View.VISIBLE);


        }

    }


    @OnClick({R.id.iv_basicalinfo_pic1, R.id.iv_basicalinfo_pic2, R.id.iv_basicalinfo_pic4, R.id.btn_basicalinfo_confirm,R.id.btn_basicalinfo_pic1,R.id.btn_basicalinfo_pic2,R.id.btn_basicalinfo_pic4})
    public void clickEvent(View view) {
        Intent intent = null;
        savaInfo();
        switch (view.getId()) {


            //pic1
            case R.id.iv_basicalinfo_pic1:


                if ("0".equals(ConstantsUser.isEdit)) {
                    intent = new Intent(mContext, ShowPhotoActivity.class);
                    intent.putExtra("phototype", "1");
                    startActivity(intent);
                    overridePendingTransition(R.anim.enter_anim, R.anim.exit_anim);
                } else {
                    PhtotUtils.takePhoto(this, file, 1);
                }
                break;


            //pic2
            case R.id.iv_basicalinfo_pic2:


                if ("0".equals(ConstantsUser.isEdit)) {
                    intent = new Intent(mContext, ShowPhotoActivity.class);
                    intent.putExtra("phototype", "2");
                    startActivity(intent);
                    overridePendingTransition(R.anim.enter_anim, R.anim.exit_anim);
                } else {
                    PhtotUtils.takePhoto(this, file, 2);
                }
                break;




            //pic4
            case R.id.iv_basicalinfo_pic4:


                if ("0".equals(ConstantsUser.isEdit)) {
                    intent = new Intent(mContext, ShowPhotoActivity.class);
                    intent.putExtra("phototype", "4");
                    startActivity(intent);
                    overridePendingTransition(R.anim.enter_anim, R.anim.exit_anim);
                } else {
                    PhtotUtils.takePhoto(this, file, 4);
                }
                break;


            //确认提交
            case R.id.btn_basicalinfo_confirm:

                if (checkPass()) {
                    submit();
                }
                break;


            //btn_basicalinfo_pic1
            case R.id.btn_basicalinfo_pic1:
                    intent = new Intent(mContext, ShowPhotoActivity.class);
                    intent.putExtra("phototype", "1_sample");
                    startActivity(intent);
                    overridePendingTransition(R.anim.enter_anim, R.anim.exit_anim);
                break;

            //btn_basicalinfo_pic2
            case R.id.btn_basicalinfo_pic2:
                    intent = new Intent(mContext, ShowPhotoActivity.class);
                    intent.putExtra("phototype", "2_sample");
                    startActivity(intent);
                    overridePendingTransition(R.anim.enter_anim, R.anim.exit_anim);

                break;

            //btn_basicalinfo_pic4
            case R.id.btn_basicalinfo_pic4:
                    intent = new Intent(mContext, ShowPhotoActivity.class);
                    intent.putExtra("phototype", "4_sample");
                    startActivity(intent);
                    overridePendingTransition(R.anim.enter_anim, R.anim.exit_anim);
                break;
        }
    }


    /**
     * 检查上传参数是否合法
     */
    private boolean checkPass() {

        if (TextUtils.isEmpty(et_basicalinfo_name.getText().toString().trim())) {
            ToastUtils.showToast("请输入正确的姓名!");
            return false;
        } else if (TextUtils.isEmpty(et_basicalinfo_identification.getText().toString().trim()) || (et_basicalinfo_identification.getText().toString().trim().length() != 15 && et_basicalinfo_identification.getText().toString().trim().length() != 18)) {
            ToastUtils.showToast("请输入正确的身份证！");
            return false;
        }else if (TextUtils.isEmpty(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC1))) {
            ToastUtils.showToast("请先上传身份证正面照！");
            return false;
        } else if (TextUtils.isEmpty(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC2))) {
            ToastUtils.showToast("请先上传身份证反面照! ");
            return false;
        }else if (TextUtils.isEmpty(SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC4))) {
            ToastUtils.showToast("请先上传手持身份证半身照! ");
            return false;
        } else {
            return true;
        }

    }


    /**
     * 提交实名认证信息
     */
    private void submit() {
        progressDialogUtils.showProgress();
        //构造传输参数
        //将参数放入map中
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("shopAccount", et_basicalinfo_name.getText().toString().trim());
        map.put("shopCert", et_basicalinfo_identification.getText().toString().trim());
        map.put("pic1", SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC1));
        map.put("pic2", SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC2));
        map.put("pic4", SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC4));
        map.put("token", SharedPreferencesUtils.getString(ConstantsUser.userToken));
        map.put("sign", Md5Utils.md5Hex(
                SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC1)
                        + SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC2)
                        + SharedPreferencesUtils.getString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC4)
                        + et_basicalinfo_name.getText().toString().trim()
                        + et_basicalinfo_identification.getText().toString().trim()
                        + SharedPreferencesUtils.getString(ConstantsUser.userKey)));

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.shopPerfectState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                progressDialogUtils.dismissProgress();

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.optString("code");
                    if (Constants.NORMAL_CODE.equals(code)) {

                        AlertDialogUtils.showAlertDialog(mContext, "商户基本信息提交成功！请等待审核通过！", new AlertInterface() {
                            @Override
                            public void confirm(Dialog alertDialog) {
                                startActivityThenKill(PersionalinfoActivity.class);
                            }
                        });
                    } else {
                        AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {

                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.fail_to_connect_server));

            }
        });


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == 1 && resultCode == RESULT_OK) {

            // 对拍照之后的图片进行压缩。
            final Bitmap bitmap = PhtotUtils.compressBySize(file.getPath(), 600, 400);
            //显示图片
            iv_basicalinfo_pic1.setImageBitmap(bitmap);
            final Bitmap b = PhtotUtils.compressImage(bitmap);
            progressDialogUtils.showProgress("正在上传照片...");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    uploadFile(b, "1");
                }
            }).start();

        } else if (requestCode == 2 && resultCode == RESULT_OK) {
            // 对拍照之后的图片进行压缩。
            final Bitmap bitmap = PhtotUtils.compressBySize(file.getPath(), 600, 400);
            final Bitmap b = PhtotUtils.compressImage(bitmap);
            //显示图片
            iv_basicalinfo_pic2.setImageBitmap(bitmap);
            progressDialogUtils.showProgress("正在上传照片...");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    uploadFile(b, "2");
                }
            }).start();
        }  else if (requestCode == 4 && resultCode == RESULT_OK) {
            // 对拍照之后的图片进行压缩。
            final Bitmap bitmap = PhtotUtils.compressBySize(file.getPath(), 600, 400);
            final Bitmap b = PhtotUtils.compressImage(bitmap);
            //显示图片
            iv_basicalinfo_pic4.setImageBitmap(bitmap);
            //开启多线程将照片上传到服务器
            progressDialogUtils.showProgress("正在上传照片...");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    uploadFile(b, "4");
                }
            }).start();

        }

    }


    /**
     * 上传照片
     */
    private void uploadFile(Bitmap bitmap, final String type) {


        //将图片写到out中
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        String fileBase64 = Base64.encodeToString(out.toByteArray(), 0, out.toByteArray().length, Base64.DEFAULT);
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        //将图片的字节流数据加密成base64字符输出
        fileBase64 = "data:image/png;base64," + fileBase64;
        String token = SharedPreferencesUtils.getString(ConstantsUser.userToken);
        //MD5（picNbr+key）
        String sign = Md5Utils.md5Hex(SharedPreferencesUtils.getString(ConstantsUser.userKey));


        //将参数放入map中
        HashMap<String, String> map = new HashMap<String, String>();


        map.put("fileBase64", fileBase64);
        map.put("token", token);
        map.put("sign", sign);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL_IMAGE, HttpActions.FileUploadState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                progressDialogUtils.dismissProgress();

                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String code = jsonObject.optString("code");
                    if (Constants.NORMAL_CODE.equals(code)) {

                        ToastUtils.showToast("照片上传成功！");
                        switch (type) {
                            case "1":
                                SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC1, jsonObject.optString("httpPath"));
                                break;
                            case "2":
                                SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC2, jsonObject.optString("httpPath"));
                                break;
                            case "3":
                                SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC3, jsonObject.optString("httpPath"));
                                break;
                            case "4":
                                SharedPreferencesUtils.putString(SharedPreferencesUtils.getString(ConstantsUser.phone) + ConstantsUser.PIC4, jsonObject.optString("httpPath"));
                                break;
                        }


                    } else {

                        AlertDialogUtils.showAlertDialog(mContext, jsonObject.optString("msg"));

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.json_parse_error));
                }
            }

            @Override
            public void onError(VolleyError volleyError) {

                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, getResources().getString(R.string.fail_to_connect_server));
            }
        });

  }



}

